package mest.util;


import org.apache.commons.io.FileUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;


public class PropertiesUtil {

    public  void UpdateProperties(String dbName) throws Exception {
        ApplicationHome applicationHome = new ApplicationHome(PropertiesUtil.class);
        String rootPath = applicationHome.getSource().getParentFile().toString();
        String fileName = "/mybatis-config.xml";
        String filePath=rootPath+fileName;
        try {
            //获取类路径下的指定文件流
            InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);
            FileUtils.copyInputStreamToFile(Objects.requireNonNull(in, "文件找不到"), new File(filePath));

            //创建dom4j解析器
            SAXReader reader = new SAXReader();
            //获取Document节点
            Document document = reader.read(new File(filePath));
            //Document document = reader.read(new File("src/main/resources/mybatis-config.xml"));
            document.addDocType("configuration", "-//mybatis.org//DTD Config 3.0//EN", "http://mybatis.org/dtd/mybatis-3-config.dtd");
            Element root = document.getRootElement();
            List<Element> elementList = root.elements();
            for (int i = 0; i < elementList.size(); i++) {
                Element element = (Element) elementList.get(i);
                List<Element> elementRoot = element.elements(); //子节点遍历
                Attribute val = elementRoot.get(0).attribute("value");
                val.setValue(dbName);
            }
            OutputFormat format = OutputFormat.createPrettyPrint();  //格式化为缩进格式
            format.setEncoding("UTF-8");  //设置编码格式
            XMLWriter writer = new XMLWriter(new FileWriter(filePath), format);
            writer.write(document);  //写入数据
            writer.close();
            System.out.print("modify over!");
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

    public static void main(String[] args) throws IOException {
        //  PropertiesUtil.UpdateProperties();
    }
}
